﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Xml;
using System.IO;

namespace FOBTV.Web.DBUtility.ManagerImpl
{
	public static class YOCOSDa
	{
		private static Dictionary<Type, object> s_classInstances = new Dictionary<Type, object>();

		private static INewsDaManager s_newsmanager = null;
		public static INewsDaManager NewsManager
		{
			get
			{
				if (s_newsmanager == null)
				{
					s_newsmanager = (INewsDaManager)s_classInstances[typeof(INewsDaManager)];
				}
				return s_newsmanager;
			}
		}

		public static void Initialize(string binPath)
		{
			try
			{
				XmlDocument xmlDoc = new XmlDocument();
				XmlNode nodeServices = null;

				Environment.CurrentDirectory = binPath;
				xmlDoc.Load(Path.Combine(binPath, "DataServices.config"));
				nodeServices = xmlDoc.SelectSingleNode("/configuration/services[1]");

				if (nodeServices != null)
				{
					string assembly = nodeServices.Attributes["assembly"].Value;

					foreach (XmlNode nodeService in nodeServices.ChildNodes)
					{
						string typeName = nodeService.Attributes["interface"].Value;
						Type type = Type.GetType(typeName);
						string implementation = nodeService.Attributes["implementation"].Value;
						object instance = Activator.CreateInstance(assembly, implementation).Unwrap();

						if (type == null)
						{
							throw new Exception("Can't retrieve the type - " + typeName);
						}
						s_classInstances.Add(type, instance);
					}
				}
			}
			catch (Exception ex)
			{
				throw new Exception("Error occurred in instantiating Manager classes.", ex);
			}
		}

	}
}